package integral

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/app/business/api/internal/repository/integral"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizintegral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralwallet"
	"private-domain-overseas-service/tools/ent/hzintegralwalletrecord"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralRewardReceiveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 领取新用户奖励积分
func NewIntegralRewardReceiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralRewardReceiveLogic {
	return &IntegralRewardReceiveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralRewardReceiveLogic) IntegralRewardReceive(req *types.IntegralRewardReceiveRequest) error {
	integralWalletDao := integral.NewIntegralWalletDao(l.ctx, l.svcCtx)
	integralWalletRecordDao := integral.NewIntegralWalletRecordDao(l.ctx, l.svcCtx)

	//定义换算值
	baiDecimal := decimal.NewFromInt(100)
	// 获取用户信息
	userId := common.JwtAuthUserId(l.ctx)

	//查询用户是否领取过新人优惠
	walletRecordConditions := make([]predicate.HzIntegralWalletRecord, 0)
	walletRecordConditions = append(walletRecordConditions, hzintegralwalletrecord.RecordTypeEQ(bizintegral.NewUserReward), hzintegralwalletrecord.UserIDEQ(userId))
	first, _ := integralWalletRecordDao.WalletRecordConditionsFirst(walletRecordConditions)
	if first != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, "该用户已领取过新人奖励积分")
	}

	//将请求中的积分转换为精度数
	integralYuan, _ := decimal.NewFromString(req.Integral)

	//构建积分钱包查询条件
	integralWalletConditions := make([]predicate.HzIntegralWallet, 0)
	integralWalletConditions = append(integralWalletConditions, hzintegralwallet.UserIDEQ(userId))
	integralWalletInfo, err := integralWalletDao.IntegralWalletConditionsOnly(integralWalletConditions)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询用户积分钱包失败：%v", err))
	}

	//执行事务
	err = common.WithTx(l.ctx, l.svcCtx.Orm, func(tx *ent.Tx) error {
		//更新用户钱包
		integralWalletInfo.WalletActiveBalance = integralWalletInfo.WalletActiveBalance + integralYuan.Mul(baiDecimal).IntPart()
		err = integralWalletDao.UpdateIntegralWallet(tx, integralWalletInfo)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("更新用户积分钱包失败：%v", err))
		}

		//添加积分变更记录
		integralWalletRecordCreate := &ent.HzIntegralWalletRecord{
			UserID:              userId,
			IntegralWalletID:    int64(integralWalletInfo.ID),
			RecordTitle:         "奖励积分",
			RecordNumber:        fmt.Sprintf("%s%d", "IW", common.Snowflake()),
			RecordAmount:        integralYuan.Mul(baiDecimal).IntPart(),
			RecordStatus:        bizintegral.Income,
			RecordType:          bizintegral.NewUserReward,
			RecordActiveBalance: integralWalletInfo.WalletActiveBalance,
			RecordFreezeBalance: integralWalletInfo.WalletFreezeBalance,
		}
		err = integralWalletRecordDao.CreateIntegralWalletRecord(tx, integralWalletRecordCreate)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("添加用户积分钱包记录失败：%v", err))
		}
		return nil
	})
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("领取新用户奖励积分失败：%v", err))
	}

	return nil
}
